package cn.piesat.scanning.utils;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import cn.piesat.scanning.vo.DownloadFileInfo;
import cn.piesat.scanning.vo.ElemRectBean;
import cn.piesat.scanning.vo.RestUtil;
import cn.piesat.scanning.vo.ResultBean;
import org.apache.commons.lang3.StringUtils;

import java.util.*;


/**
 * Cimiss调用接口API
 * @author 陈波
 *
 */
public class CimissInterfaceAPI {
	private String cimissUrlHead;
	
	public CimissInterfaceAPI(String ip,String port,String userid,String password){
		this.cimissUrlHead  =  "http://" + ip+":"+port+ "/cimiss-web/api?userId="+userid+"&pwd="+password;
	}
	
	public CimissInterfaceAPI(String url){
		this.cimissUrlHead  =  url;
	}
	
	/**
	 * 获取文件类型数据
	 * @param methodName 方法名 
	 * @param dataCode 方法参数  。格式 ：&参数名=参数值
	 * @return ResultBean
	 */
	public ResultBean getFileData(String methodName, String dataCode, String timeRange){
		String methodParams ="&interfaceId="+ methodName +"&dataCode="+ dataCode +"&timeRange="+ timeRange +"&dataFormat=json";
		return getFileOrStationData(methodParams, 0);
	}
	
	/**
	 * 获取Grid类型数据
	 * @param args 方法名
	 * @return
	 */
	public  ResultBean getGridData(Map<String,String> args){
		Set<String> set = args.keySet();
		
		String methodParams = "";
		if(!args.isEmpty()){
			for(String field : set){
				String value = args.get(field);
				methodParams = methodParams + "&"+field +"="+ value ;
			}
		}
		
		return getFileOrStationData(methodParams, 1);
	}
	
	/**
	 * 格点场数据
	 * @param methodName 方法名 
	 * @param dataCode 方法参数  。格式 ：&参数名=参数值
	 * @param  
	 * @return
	 */
	public ElemRectBean getElemRectData(String methodName, String dataCode, String timeRange){
		String methodParams ="&interfaceId="+ methodName +"&dataCode="+ dataCode +"&timeRange="+ timeRange +"&dataFormat=json";
		String url = this.cimissUrlHead + methodParams;
		
		ElemRectBean elemRectBean = new ElemRectBean();
		
	    RestUtil restUtil = new RestUtil() ;
	    String formatJson = restUtil.getRestData(url) ;
	    
	    if("".equals(formatJson) || formatJson == null){
	    	elemRectBean.setReturnCode("-1");
	    	elemRectBean.setReturnMessage("No result for request");
	    	elemRectBean.setRowCount("0");
	    	elemRectBean.setColCount("0");
	    }else {
	    	JSONObject jsonObject= JSONObject.parseObject(formatJson);
		    
		    String returnCode = (String)jsonObject.get("returnCode");
		    elemRectBean.setReturnCode(returnCode);//返回代码
		    elemRectBean.setReturnMessage((String)jsonObject.get("returnMessage"));
		    elemRectBean.setRequestParams((String)jsonObject.get("requestParams"));
		    elemRectBean.setRequestTime((String)jsonObject.get("requestTime"));
		    elemRectBean.setResponseTime((String)jsonObject.get("responseTime"));
		    elemRectBean.setTakeTime((String)jsonObject.get("takeTime"));
		    
		    if(returnCode != null && returnCode.equals("0")){
		    	setElemRectResult(elemRectBean,jsonObject);
		    }else {
		    	elemRectBean.setRowCount((String)jsonObject.get("rowCount"));
			    elemRectBean.setColCount((String)jsonObject.get("colCount"));
			}
	    }
		return elemRectBean;
	}
	
	/**
	 * 
	 * @param paramsMap 调用接口参数 key参数名 : value参数值
	 * @return
	 */
	public static String getURLParamsByMap(Map<String, String> paramsMap){
		//获取参数名集合 Map中的key集合
		Set<String> set = paramsMap.keySet();
		
		String paramStr = "";
		
		//拼接url中参数部分
		for(String param : set){
			String paramValue = paramsMap.get(param);
			paramStr = paramStr + "&" + param + "=" + paramValue;
		}
		
		return paramStr;
	}
	
	
	
	private  ResultBean getFileOrStationData(String URLParamsPart,int type){
		String url = "";
		if(URLParamsPart!=null && !URLParamsPart.equals("")){
			url = this.cimissUrlHead + URLParamsPart;
		}else{
			url = this.cimissUrlHead;
		}
		
		ResultBean resultBean = new ResultBean();
		
	    RestUtil restUtil = new RestUtil() ;
	    String formatJson = restUtil.getRestData(url) ;
		if(formatJson == null || formatJson.equals("")){
			return null;
		}
	    
	    if("".equals(formatJson) || formatJson == null){
	    	 resultBean.setReturnCode("-1");
	    	 resultBean.setReturnMessage("No result for request");
	    	 resultBean.setRowCount("0");
	    	 resultBean.setColCount("0");
	    }else {
	    	JSONObject jsonObject= JSONObject.parseObject(formatJson);
		    
		    String returnCode = (String)jsonObject.get("returnCode");
		    resultBean.setReturnCode(returnCode);//返回代码
		    resultBean.setReturnMessage((String)jsonObject.get("returnMessage"));
		    if(type == 0){
		    	resultBean.setRowCount((String)jsonObject.get("fileCount"));
		    }else {
		    	resultBean.setRowCount((String)jsonObject.get("rowCount"));
			}
		    resultBean.setColCount((String)jsonObject.get("colCount"));
		    resultBean.setRequestParams((String)jsonObject.get("requestParams"));
		    resultBean.setRequestTime((String)jsonObject.get("requestTime"));
		    resultBean.setResponseTime((String)jsonObject.get("responseTime"));
		    resultBean.setTakeTime((String)jsonObject.get("takeTime"));
		    
		    if((String)jsonObject.get("fieldNames") != null){
		    	String fileName = (String)jsonObject.get("fieldNames");
		    	String[] fileNames = fileName.split(" ");
            	resultBean.setFieldNames(fileNames);
            }
		    
		    if((String)jsonObject.get("fieldUnits") != null){
		    	String fieldUnit = (String)jsonObject.get("fieldUnits");
		    	String[] fieldUnits = fieldUnit.split(" ");
            	resultBean.setFieldUnits(fieldUnits);
            }
		    
		    if(returnCode != null && returnCode.equals("0")){
		    	JSONArray array = jsonObject.getJSONArray("DS");
		    	if(type == 0){
					setFileResult(resultBean,array);
				}else {
					setGridResult(resultBean,array);
				}
		    }
	    }
	    
		return resultBean;
	}
	
	

	/**
	 * file数据  DS解析
	 * @param array
	 * @return
	 */
	private  void setFileResult(ResultBean resultBean,JSONArray array){

    	List<DownloadFileInfo> data = new ArrayList<DownloadFileInfo>();
 
    	for (int i = 0; i < array.size(); i++) {
            JSONObject obj = array.getJSONObject(i);
            DownloadFileInfo info = new DownloadFileInfo();
            info.setFileName(obj.getString("FILE_NAME"));
            info.setFileSize(obj.getString("FILE_SIZE"));
            info.setFormat(obj.getString("FORMAT"));
            info.setFileURL(obj.getString("FILE_URL"));
            data.add(info);
           
        }
    	resultBean.setData(data);

	}
	
	/**
	 * grid数据 DS解析
	 * @param array
	 * @return
	 */
	
	private  void setGridResult(ResultBean resultBean, JSONArray array){
    	List<Map<String, String>> dataList = new ArrayList<Map<String, String>>();
    	
    	String requestParams = resultBean.getRequestParams();
    	String[] params = requestParams.split("&");
    	String  element = null;
    	for(String param : params){
    		if(param.indexOf("elements")>-1){
    			element = param;
    			break;
    		}
    	}
    	
    	String elementValue = element.substring(element.indexOf("=")+1);
    	String[] elements = elementValue.split(",");//字段数组
    
    	for (int i = 0; i < array.size(); i++) {
            JSONObject obj = array.getJSONObject(i);
            Map<String, String> dataMap = new HashMap<String, String>();
            for(String field : elements){
            	dataMap.put(field, StringUtils.isEmpty(obj.getString(field))?null: obj.getString(field));
            }
            dataList.add(dataMap);//将map存入list集合中
        }
    	resultBean.setData(dataList);
	}
	
	/**
	 * ElemRect数据 DS解析
	 * @param elemRectBean
	 * @return
	 */
	
	private  void setElemRectResult(ElemRectBean elemRectBean, JSONObject jsonObject){
		elemRectBean.setStartLat((String)jsonObject.get("startLat"));
		elemRectBean.setStartLon((String)jsonObject.get("startLon"));
		elemRectBean.setEndLat((String)jsonObject.get("endLat"));
		elemRectBean.setEndLon((String)jsonObject.get("endLon"));
		
		String latCount = (String)jsonObject.get("latCount");
		int row = Integer.parseInt(latCount);
		elemRectBean.setLatCount(latCount);
		String lonCount = (String)jsonObject.get("lonCount");
		int col = Integer.parseInt(lonCount);
		elemRectBean.setLonCount(lonCount);
		
		elemRectBean.setLonStep((String)jsonObject.get("lonStep"));
		elemRectBean.setLatStep((String)jsonObject.get("latStep"));
		
		String[][] lonAndLat = new String[row][col];
		JSONArray array = jsonObject.getJSONArray("DS");
    	
    	for (int i = 0; i < array.size(); i++) {
    		JSONArray array1 = (JSONArray)array.get(i);
            String[] data = new String[col];
           for(int j = 0; j < array1.size(); j++){
        	   data[j] = (String) array1.get(j);
           }
           lonAndLat[i] = data;
        }
    	elemRectBean.setLonAndLat(lonAndLat);
	}
	
	
	public static void main(String[] args) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("returnCode", "0");
		String[][] DSStr = {{"299.2126","299.31018","299.53098","299.7158"},{"299.3878","299.34216","299.0894","298.96857"}};
		jsonObject.put("DS", DSStr);

	    String returnCode = (String)jsonObject.get("returnCode");

	    JSONArray array = jsonObject.getJSONArray("DS");
	    String[][] data = new String[2][4];
	    
	    for (int i = 0; i < array.size(); i++) {
	    	JSONArray array1 = (JSONArray)array.get(i);
	    	String[] data2 = new String[4];
	    	for(int j = 0; j < array1.size(); j++){
	    		data2[j] = (String) array1.get(j);
 	    	}
	    	data[i] = data2;
        }
	}
}
